import find_mxnet
import mxnet as mx
import logging
import numpy as np
import codecs
import json
from PIL import Image

import os
# Note: The decoded image should be in BGR channel (opencv output)
# For RGB output such as from skimage, we need to convert it to BGR
# WRONG channel will lead to WRONG result
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

prefix = "img"
num_round = 20
model = mx.model.FeedForward.load(prefix, num_round, ctx=mx.cpu(), numpy_batch_size=1)
#mean_img = mx.nd.load("/home/spark/train_data/img_10min_full_gray_data/mean.bin")["mean_img"]
mean_img = mx.nd.load("/home/spark/train_data/img_10_data0/mean.bin")["mean_img"]

"""
with codecs.open('synset2.txt', 'r', 'utf-8') as f2:
    synset = f2.readlines()
"""

batch_size = 1
data_shape = (1, 80, 80)

json_test = '{"time":"09:20:22",' \
           '"length":72,' \
           '"list":' \
           '[{"jd":104.045086,"wd":30.681398},' \
           '{"jd":104.048019,"wd":30.678498},' \
           '{"jd":104.051516,"wd":30.676068},' \
           '{"jd":104.052701,"wd":30.675345},' \
           '{"jd":104.054629,"wd":30.674357},' \
           '{"jd":104.057654,"wd":30.672977},' \
           '{"jd":104.057879,"wd":30.672780},' \
           '{"jd":104.056298,"wd":30.669392},' \
           '{"jd":104.056121,"wd":30.668046},' \
           '{"jd":104.055859,"wd":30.667718},' \
           '{"jd":104.055780,"wd":30.667641},' \
           '{"jd":104.053865,"wd":30.668607}]}' \


def PreprocessImage(json_str, show_img=False):
    # load image
    data = json.loads(json_str)
    print data
    print data['list']
    im = np.ones([80, 80, 1]) * 0.0
    tim = data['time']
    tim = tim.split(":")
    dotvalue = int(tim[0])/24.0
    for dot in data['list']:
        xi = dot['jd'] - 104.03
        xi = int(xi * 1000)
        yi = dot['wd'] - 30.620
        yi = int(yi * 1000)
        im[xi, yi] = dotvalue
    """
    gray()
    if show_img:
        io.imshow(im)
        show()
    """
    # convert to numpy.ndarray
    sample = np.asarray(im) * 256  #?
    sample.resize(1,1,80,80)
    normed_img = sample - mean_img.asnumpy()
    #print shape(normed_img)
    #normed_img=normed_img.reshape(1, 1, 80, 80)
    return normed_img
mp = {
    "1":"1--10",
    "2":"11--20",
    "3":"21--30",
    "4":"31--40",
    "5":"41--50",
    "6":"51--60",
    "7":"61--70",
}
def predict(json_str):
    batch = PreprocessImage(json_str, True)
    prediction = model.predict(batch)[0]
    #print prediction.size #number of the label
    key = str(prediction.argmax())
    #print mp[key]
    output = "the prediction is %s, the Probability is %f"%(mp[key],prediction.max())
    print output
    return output

def main():
    predict(json_test)

if __name__ == "__main__":
    main()

"""
how to print the p
label=synset[prediction.argmax()]
#print str(label)
print label
print prediction.max()
#print str(prediction[label])
"""
